package com.example.lesson

import android.util.Log
import com.example.core.http.EntityCallback
import com.example.core.http.HttpClient
import com.example.core.utils.toast
import com.example.lesson.entity.Lesson
import com.google.gson.reflect.TypeToken
import java.lang.reflect.Type

class LessonPresenter {
    companion object{
        private const  val  LESSON_PATH  = "lessons";

    }
    private lateinit var activity:LessonActivity
    constructor(activity:LessonActivity){
        this.activity=activity
    }
    private var lessons:List<Lesson> =   ArrayList();
    private val  type: Type = object:  TypeToken<List<Lesson>>() {
    }.type
    fun fetchData() {
        HttpClient.INSTANCE.get(LESSON_PATH, type,
                object: EntityCallback<List<Lesson?>> {
                    override fun onSuccess(entity: List<Lesson?>) {
                        this@LessonPresenter.lessons = lessons;
                        activity.runOnUiThread(object: Runnable   {
                            @Override
                              override fun run() {
                                activity.showResult(lessons);
                            }
                        });
                    }

                    override fun onFailure(message: String) {
                        activity.runOnUiThread(object: Runnable  {
                            @Override
                            override fun run() {
                                toast(message);
                            }
                        });
                    }
                })

    }
    fun showPlayback() {
        //原代码 过滤集合中指定类型的数据
//        var playbackLessons =   arrayListOf<Lesson>()
//        for ( lesson in lessons) {
//            if (lesson.state == Lesson.State.PLAYBACK) {
//                playbackLessons.add(lesson);
//            }
//        }
//        activity.showResult(playbackLessons);

        //优化代码 使用集合的forEach遍历
//        var playbackLessons =   arrayListOf<Lesson>()
//        lessons.forEach {
//            if (it.state == Lesson.State.PLAYBACK) {
//                playbackLessons.add(it)
//            }
//        }
//        activity.showResult(playbackLessons);

        //再优化 使用集合的过滤函数filter，类似rxjava的过滤操作符
//        val filter = lessons.filter { it.state == Lesson.State.PLAYBACK  }
//        activity.showResult(filter);

        //再优化  filter过滤
        activity.showResult(lessons.filter { it.state == Lesson.State.PLAYBACK  });

    }

}